package com.csxy.lsh.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csxy.lsh.entity.EduSubject;
import com.csxy.lsh.entity.excel.SubjectData;
import com.csxy.lsh.exception.MyException;
import com.csxy.lsh.service.EduSubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData > {
    public EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }
public SubjectExcelListener(){

}
@Override
public  void  invoke (SubjectData subjectData,AnalysisContext analysisContext){
    if (subjectData==null){
        throw new MyException(20001,"添加失败");
    }

    EduSubject existOneSubject=this.existOneSubject(eduSubjectService,subjectData.getOneSubjectName());
    if (existOneSubject==null){
        existOneSubject=new EduSubject();
        existOneSubject.setParentId("0");
        existOneSubject.setTitle(subjectData.getOneSubjectName());
        eduSubjectService.save(existOneSubject);

    }



String parent_id=existOneSubject.getId();

    EduSubject existTwoSubject=this.existTwoSubject(eduSubjectService, subjectData.getTwoSubjectName(),parent_id);
    if (existTwoSubject==null){
        existTwoSubject=new EduSubject();
        existTwoSubject.setParentId(parent_id);
        existTwoSubject.setTitle(subjectData.getTwoSubjectName());
        eduSubjectService.save(existTwoSubject);
    }
}


private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
    QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
    wrapper.eq("title",name)
            .eq("parent_id","0");
    EduSubject oneSubject = eduSubjectService.getOne(wrapper);
    return oneSubject;
}
private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String parentId,String name){
    QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
    wrapper.eq("title",name)
            .eq("parent_id","0");
    EduSubject twoSubject = eduSubjectService.getOne(wrapper);
    return twoSubject;

}

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}




